<?php

namespace framework\support;

use framework\libraries\ErrorType;
use framework\libraries\Stdio;

class Response
{
    static function success($data = null)
    {
        $res = [
            'code' => 0,
            'msg' => 'ok',
        ];
        if ($data) {
            $res['data'] = $data;
        }
        echo json_encode($res);
    }

    static function error($code, $msg = "", $data = null)
    {
        $errorCode = require_once(BasePath . '/app/config/error.php');
        $tips = $errorCode[$code] ?? ErrorType::messages[$code] ?? null;
        if ($tips) {
            $msg = $tips . ":" . $msg;
        }
        header('Content-Type: application/json; charset=utf-8');
        $res = [
            'code' => $code,
            'msg' => $msg,
        ];
        if ($data) {
            $res['data'] = $data;
        }
        Stdio::println($res);
        echo json_encode($res);
    }

    static function redirect($url)
    {
        header('Location: ' . $url);
    }

    static function  header($name,  bool $replace = true, int $http_response_code = null)
    {
        header($name, $replace, $http_response_code);
    }

    static function raw($httpCode, $data = null)
    {
        header('HTTP/1.1 ' . $httpCode);
        echo $data;
    }
}
